package cmd

import (
	"fmt"
	"time"

	"google.golang.org/grpc/balancer/roundrobin"
	"google.golang.org/grpc/resolver"
	"google.golang.org/grpc/resolver/manual"

	pb "gitee.com/zfd81/dbrs/proto/dbrspb"

	"google.golang.org/grpc"
)

type GlobalFlags struct {
	Endpoints []string
	User      string
	Password  string
}

func GetConnection(endpoint string) (*grpc.ClientConn, error) {
	conn, err := grpc.Dial(endpoint, grpc.WithInsecure(), grpc.WithBlock(), grpc.WithTimeout(3*time.Second))
	if err != nil {
		return nil, fmt.Errorf("did not connect, %v\n", err)
	}
	return conn, nil
}

func GetBrokerSystemClient(endpoint string) (pb.BrokerSystemClient, error) {
	conn, err := GetConnection(endpoint)
	if err != nil {
		return nil, err
	}
	return pb.NewBrokerSystemClient(conn), nil
}

func GetConn() (*grpc.ClientConn, error) {
	var addresses []resolver.Address
	for _, endpoint := range globalFlags.Endpoints {
		addresses = append(addresses, resolver.Address{Addr: endpoint})
	}

	r := manual.NewBuilderWithScheme("whatever")
	r.InitialState(resolver.State{Addresses: addresses})
	conn, err := grpc.Dial(
		r.Scheme()+":///grpcs.server",
		grpc.WithInsecure(),
		grpc.WithResolvers(r),
		grpc.WithDefaultServiceConfig(fmt.Sprintf(`{"LoadBalancingPolicy": "%s", "RetryPolicy": {"MaxAttempts":2, "InitialBackoff": "0.1s", "MaxBackoff": "1s", "BackoffMultiplier": 2.0, "RetryableStatusCodes": ["UNAVAILABLE"]}}`, roundrobin.Name)),
		grpc.WithBlock(),
		grpc.WithTimeout(3*time.Second))
	if err != nil {
		return nil, fmt.Errorf("did not connect: %v", err)
	}
	return conn, nil
}

func BrokerSystemClient() (pb.BrokerSystemClient, error) {
	conn, err := GetConn()
	if err != nil {
		return nil, err
	}
	return pb.NewBrokerSystemClient(conn), nil
}
